<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入居民姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="queryParams.idCard"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <el-button type="primary" :icon="Plus" @click="handleAdd"
          >新增居民</el-button
        >
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="residentList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="name"
          label="姓名"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="phone"
          label="手机号"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="idCard"
          label="身份证号"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === "Male" ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="birthDate"
          label="出生日期"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="居住地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Edit, Delete } from "@element-plus/icons-vue";
import { getResidents, deleteResident } from "@/api/resident";

const router = useRouter();

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  idCard: "",
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const residentList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 获取居民列表
const getList = async () => {
  try {
    loading.value = true;
    const res = await getResidents(queryParams.value);
    residentList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取居民列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增居民
const handleAdd = () => {
  router.push("/resident/add");
};

// 编辑居民
const handleEdit = (row) => {
  router.push(`/resident/edit/${row.id}`);
};

// 删除居民
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除居民 ${row.name} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteResident(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleDateString();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
